package com.lap.permission.manager.impl;

import com.lap.permission.dal.DictDetailDAO;
import com.lap.permission.dal.DictDAO;
import com.lap.permission.domain.entity.Dict;
import com.lap.permission.domain.entity.DictDetail;
import com.lap.permission.manager.DictManager;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@RequiredArgsConstructor
@Service
public class DictManagerImpl implements DictManager {

    private final DictDAO dictDAO;

    private final DictDetailDAO dictDetailDAO;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer insertDict(Dict dict, List<DictDetail> dataList) {
        dictDAO.insertDict(dict);
        if (!dataList.isEmpty()) {
            prepareDictDetails(dict, dataList);
            dictDetailDAO.insertDictDetailBatch(dataList);
        }
        return dict.getId();
    }

    private void prepareDictDetails(Dict dict, List<DictDetail> dataList) {
        dataList.forEach(detail -> {
            detail.setDictId(dict.getId());
            detail.setDictCode(dict.getCode());
        });
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteById(Integer dictId) {
        dictDetailDAO.deleteByDictId(dictId);
        return dictDAO.deleteById(dictId);
    }

}
